<template>
    <div class="list-wrapper">
        <Block>
            <DataGrid :auto-load="autoLoad" row-key="id" border ref="dataGridRef">
                <template #toolbar-search>
                    <div class="query-from-box">
                        <el-form>
                            <el-form-item>
                                <el-input
                                    v-model="queryData.deviceKey"
                                    placeholder="设备名称/标识符/设备编号"
                                    clearable
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-input v-model="queryData.productKey" placeholder="产品/标识符" clearable />
                            </el-form-item>
                            <el-form-item>
                                <el-tree-select
                                    placeholder="产品标签"
                                    v-model="queryData.productLabels"
                                    :data="productLabelTree"
                                    :props="defaultProps"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    check-strictly
                                    :render-after-expand="false"
                                    show-checkbox
                                    clearable
                                    node-key="labelNo"
                                    @visible-change="getProductLabelTree"
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-tree-select
                                    placeholder="设备标签"
                                    v-model="queryData.labels"
                                    :data="labelTree"
                                    :props="defaultProps"
                                    multiple
                                    collapse-tags
                                    collapse-tags-tooltip
                                    check-strictly
                                    :render-after-expand="false"
                                    show-checkbox
                                    clearable
                                    node-key="labelNo"
                                    @visible-change="getLabelTree"
                                />
                            </el-form-item>
                            <el-form-item>
                                <el-select v-model="queryData.enabled" placeholder="启用状态" clearable>
                                    <el-option
                                        v-for="(value, key) in ProductState"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                            <el-form-item>
                                <el-select placeholder="在线状态" v-model="queryData.deviceStatus" clearable>
                                    <el-option
                                        v-for="(value, key) in DeviceStatus"
                                        :label="value"
                                        :key="key"
                                        :value="key"
                                    />
                                </el-select>
                            </el-form-item>
                        </el-form>
                    </div>
                </template>
                <template #toolbar-operation v-if="checkPermi(['iot:device:edit'])">
                    <el-button type="primary" @click="onCreate">新建</el-button>
                    <el-button type="primary" plain @click="onImport">导入</el-button>
                    <el-button @click="onExport">导出</el-button>
                </template>
                <el-table-column type="index" label="序号" width="60" align="center" fixed />
                <el-table-column label="设备名称" width="300" fixed show-overflow-tooltip>
                    <template #default="scope">
                        <el-button link type="primary" @click="onGoDetail(scope.row)">
                            {{ scope.row.deviceName }}
                        </el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="id" label="标识符" show-overflow-tooltip />
                <el-table-column prop="deviceNo" label="设备编号" show-overflow-tooltip />
                <el-table-column prop="productName" label="产品" show-overflow-tooltip />
                <el-table-column label="产品标签" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.productLabelNames ? scope.row.productLabelNames.join('；') : '' }}
                    </template>
                </el-table-column>
                <el-table-column label="设备标签" show-overflow-tooltip>
                    <template #default="scope">
                        {{ scope.row.labelNames ? scope.row.labelNames.join('；') : '' }}
                    </template>
                </el-table-column>

                <el-table-column label="启用状态" width="65">
                    <template #default="scope">
                        <span class="table-item-status" :status="scope.row.enabled ? '启用' : '停用'">
                            {{ scope.row.enabled ? '启用' : '停用' }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="在线状态" width="65">
                    <template #default="scope">
                        <span class="table-item-status" :status="DeviceStatus[scope.row.deviceStatus]">
                            {{ DeviceStatus[scope.row.deviceStatus] }}
                        </span>
                    </template>
                </el-table-column>
                <el-table-column label="节点类型" width="95">
                    <template #default="scope">
                        <div class="table-item-tag">
                            <el-tag
                                :type="
                                    scope.row.productType == 'DIRECT'
                                        ? 'success'
                                        : scope.row.productType == 'GATEWAY'
                                          ? 'primary'
                                          : 'warning'
                                "
                                >{{ ProductType[scope.row.productType] }}</el-tag
                            >
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="连网信息" show-overflow-tooltip width="180">
                    <template #default="scope">
                        <template v-if="scope.row.nbIotSerial || scope.row.nbIotRegistration">
                            NB-IoT串口号{{ scope.row.nbIotSerial || '--' }};注册{{
                                scope.row.nbIotRegistration || '--'
                            }}
                        </template>
                        <template
                            v-else-if="scope.row.networkIp || scope.row.networkPort || scope.row.networkPort == 0"
                        >
                            IP地址{{ scope.row.networkIp || '--' }}:{{
                                scope.row.networkPort || scope.row.networkPort == 0 ? scope.row.networkPort : '--'
                            }}
                        </template>
                        <template v-else-if="scope.row.serialPort || scope.row.baudRate">
                            串口号{{ scope.row.serialPort || '--' }}、波特率{{ scope.row.baudRate || '--' }}
                        </template>
                        <template v-else>--</template>
                    </template>
                </el-table-column>
                <!-- TODO：组织 -->
                <el-table-column prop="" label="组织" show-overflow-tooltip />
                <el-table-column label="操作" width="135" fixed="right" v-if="checkPermi(['iot:device:edit'])">
                    <template #default="scope">
                        <el-button link type="primary" v-if="!scope.row.enabled" @click="onEdit(scope.row)">
                            修改
                        </el-button>
                        <el-button link type="danger" @click="onDel(scope.row)" v-if="!scope.row.enabled">
                            删除
                        </el-button>
                        <!-- <el-button
                            link
                            type="primary"
                            @click="onLink(scope.row)"
                            v-if="
                                scope.row.connectMode == 'PASSIVE' &&
                                scope.row.enabled &&
                                (scope.row.deviceStatus == 'OFFLINE' || scope.row.deviceStatus == 'UNREGISTER')
                            "
                        >
                            连接
                        </el-button> -->
                        <el-button link type="primary" v-if="scope.row.enabled" @click="onDisable(scope.row)">
                            停用
                        </el-button>
                        <el-button link type="primary" v-else @click="onEnable(scope.row)"> 启用 </el-button>
                    </template>
                </el-table-column>
            </DataGrid>
        </Block>
    </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { IoTDeviceService, runLabelService } from '@great/services';
import { showPopupBox } from '@great/utils';
import { useRouter } from 'vue-router';
import { ProductType, DeviceStatus } from '@/utils/constant';
import CreateEditModal from './components/list/CreateEditModal.vue';
import ImportModal from './components/list/ImportModal.vue';
import { DataGrid, Block, type DataGridInstance } from '@great/components';
import { checkPermi } from '@/utils/ruoyi';

const router = useRouter();
enum ProductState {
    true = '启用',
    false = '停用'
}
// 查询条件
const queryData = ref({
    enabled: '',
    deviceStatus: '',
    deviceKey: '',
    productKey: '',
    labels: [],
    productLabels: []
});
const defaultProps = {
    children: 'childLabel',
    label: 'labelName',
    value: 'labelNo'
};
const labelTree = ref();
const productLabelTree = ref();
const dataGridRef = useTemplateRef<DataGridInstance>('dataGridRef');
const autoLoad = reactive({
    debounce: true,
    reloadDeps: [queryData],
    onLoad: async (current, size) => {
        const res = await IoTDeviceService.getPageDevice({
            current,
            size,
            ...queryData.value,
            labels: queryData.value.labels ? queryData.value.labels.join(',') : null,
            productLabels: queryData.value.productLabels ? queryData.value.productLabels.join(',') : null
        });
        return { data: res.data.records, total: res.data.total };
    }
});

// 创建
const onCreate = () => {
    showPopupBox(CreateEditModal, {
        callBack: dataGridRef.value?.refresh
    });
};
// 编辑
const onEdit = row => {
    showPopupBox(CreateEditModal, {
        row,
        callBack: dataGridRef.value?.refresh
    });
};
// 查看详情
const onGoDetail = (row: { id: number }) => {
    if (checkPermi(['iot:device:detail'])) {
        router.push({
            name: 'IoT-device-detail',
            params: {
                id: row?.id
            }
        });
    }
};
// 导入
const onImport = () => {
    showPopupBox(ImportModal, {
        callBack: dataGridRef.value?.refresh
    });
};
// TODO: 导出
const onExport = () => {
    //
};
// 删除
const onDel = (row: { id: number; deviceName: string }) => {
    ElMessageBox.confirm(`是否确认删除设备 ${row.deviceName} ？`, '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTDeviceService.delDevice(row?.id as number);
            ElNotification({
                title: '删除成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 停用
const onDisable = async (row: { id: number }) => {
    ElMessageBox.confirm(`确认将设备及设备下任务一起停用？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTDeviceService.disableDevice(row?.id as number);
            ElNotification({
                title: '停用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 启用
const onEnable = async (row: { id: number; deviceName: string }) => {
    ElMessageBox.confirm(`确认将启用设备${row.deviceName}？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(async () => {
            await IoTDeviceService.enableDevice(row?.id as number);
            ElNotification({
                title: '启用成功！',
                type: 'success'
            });
            dataGridRef.value?.refresh();
        })
        .catch(() => {});
};
// 连接
const onLink = async (row: Record<string, string>) => {
    await IoTDeviceService.publishDeviceStatus({
        productNo: row.productNo,
        deviceNo: row.deviceNo,
        deviceStatus: 'ONLINE'
    });
    ElNotification({
        title: '操作成功！',
        type: 'success'
    });
    dataGridRef.value?.refresh();
};
// 获取标签
const getLabelTree = async () => {
    if (labelTree.value && labelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-deviceLabel' });
    labelTree.value = res.data;
};
// 获取产品标签
const getProductLabelTree = async () => {
    if (productLabelTree.value && productLabelTree.value.length > 0) return;
    const res = await runLabelService.getLabelTree({ labelTypeNo: 'labelType-producctLabel' });
    productLabelTree.value = res.data;
};
</script>
<style scoped lang="scss">
.list-wrapper {
    .query-from-box {
        display: flex;
        align-items: center;
        .el-form {
            display: flex;
            .el-form-item {
                margin-bottom: 0;
                width: 192px;
            }
            .el-form-item + .el-form-item {
                margin-left: 10px;
            }
        }
    }
    :deep(.data-grid) {
        .table-item-tag {
            display: flex;
        }
        .table-item-status {
            display: flex;
            align-items: center;
            &::before {
                content: '';
                width: 6px;
                height: 6px;
                display: inline-block;
                border-radius: 50%;
                margin-right: 5px;
                background-color: #e6a23c;
            }
        }
        .table-item-status[status='停用'],
        .table-item-status[status='无'] {
            &::before {
                background-color: #909399;
            }
        }
        .table-item-status[status='启用'],
        .table-item-status[status='在线'] {
            &::before {
                background-color: #67c23a;
            }
        }
        .table-item-status[status='离线'] {
            &::before {
                background-color: #f56c6c;
            }
        }
    }
}
</style>
